<template>
  <div>
    <div>computed</div>
    <input type="text" v-model="obj.name" />
    <input type="text" v-model="obj.age" />
    <div>{{ cobj }}</div>
    <button @click="change">computedChange</button>

    <hr />
    <div>watch</div>
    <input type="text" v-model="message" />
    <input type="text" v-model="message2" />
    <hr />
    <div>watchEffect</div>
    <input type="text" v-model="a" />
    <button @click="stop()">stop watch</button>
    <hr />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, reactive, watchEffect } from "vue";

const obj = ref({ name: "张山", age: 12 });
const change = () => {
  obj.value.name = "ziyi";
};
const cobj = computed(() => obj.value.name + obj.value.age);

let message = ref<string>("小满");
let message2 = ref<string>("大满");

/**
 * watch和watchEffect的区别
 * 1.watchEffect 会直接直接调用一次  相当于为watch配置了immediate = true
 */

watch(
  [() => message, message2],
  (newVal, oldVal) => console.log(newVal, oldVal),
  {
    deep: true, //reactive无需开启deep，但是ref需要开启
    immediate: false, //立即执行一次
    flush: "pre", //pre组件更新之前调用 sync同步执行  post组件更新之后执行
  }
);

let a = ref("123");
const stop = watchEffect(
  (oninvalidate) => {
    oninvalidate(() => {
      // 会在更新前执行此函数
      console.log("change before");
    });
    console.log("a>>>>>>>>>", a);
  },
  {
    flush: "pre",
    onTrigger(e) {
      console.log(e);
    },
  }
);
</script>

<style lang="scss" scoped></style>
